package com.web.test.servlet;

import com.web.test.bean.Student;
import com.web.test.dao.StudentDao;
import com.web.test.utils.SQLUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017/9/23.
 */
public class LoginServlet extends HttpServlet {

    StudentDao studentDao = new StudentDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id = request.getParameter("id");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();

        if (id != null && password != null) {


            List<Student> students = null;
            try {
                students = studentDao.find(SQLUtils.getFindByStuNoAndPassSql(id, password));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (students.size() == 0) {

                session.setAttribute("isLogin", false);
                session.setAttribute("errorMsg", "账号或者密码错误");
                response.sendRedirect("webexam_login.jsp");

            } else {

                session.removeAttribute("errorMsg");

                session.setAttribute("isLogin", true);
                session.setAttribute("id",id);
                session.setAttribute("password",password);

//                request.getSession().setAttribute("students",students);
//                request.getRequestDispatcher("webexam_my_info.jsp").forward(request,response);
                response.sendRedirect("/my_info");

            }

        } else {

            response.sendRedirect("webexam_login.jsp");

        }
    }
}
